﻿#define _CRT_SECURE_NO_WARNINGS 1
#pragma warning(disable : 6031)
#include "sl.h"

sl* init()
{
	sl* phead = (sl*)malloc(sizeof(sl));
	if (!phead)
	{
		perror("malloc");
		return NULL;
	}
	phead->prev = phead;
	phead->next = phead;
	return phead;
}

void print(sl* phead)
{
	sl* cur = phead->next;
	while (cur != phead)
	{
		printf("%d->", cur->data);
		cur = cur->next;
	}
}

sl* creatsl(int x)
{
	sl* phead = (sl*)malloc(sizeof(sl));
	if (!phead)
	{
		perror("malloc");
		return NULL;
	}
	phead->prev = NULL;
	phead->next = NULL;
	phead->data = x;
	return phead;
}

void pushback(sl* phead, int x)
{
	assert(phead);
	/*sl* newnode = creatsl(x);
	sl* tail = phead->prev;
	tail->next = newnode;
	newnode->prev = tail;
	newnode->next = phead;
	phead->prev = newnode;*/

	insert(phead, x);
}

void pushfront(sl* phead, int x)
{
	assert(phead);
	/*sl* newnode = creatsl(x);

	sl* next = phead->next;
	phead->next = newnode;
	newnode->prev = phead;
	newnode->next = next;
	next->prev = newnode;*/

	insert(phead->next, x);
}

void popfront(sl* phead)
{
	assert(phead);
	assert(phead != phead->next);
	
	/*sl* tail = phead->next;
	sl* next = tail->next;
	free(tail);
	phead->next = next;
	next->prev = phead;*/
	erase(phead->next);
}

void popback(sl* phead)
{
	assert(phead);
	assert(phead != phead->next);
	
	/*sl* tail = phead->prev;
	sl* prev = tail->prev;

	free(tail);
	prev->next = phead;
	phead->prev = prev;*/

	erase(phead->prev);
}

sl* findsl(sl* phead, int x)
{
	assert(phead);
	sl* cur = phead->next;
	while (cur != phead)
	{
		if (cur->data == x)
			return cur;
		cur = cur->next;
	}
	return NULL;
}

void insert(sl* pos, int x)
{
	assert(pos);
	sl* newnode = creatsl(x);
	sl* prev = pos->prev;

	newnode->next = pos;
	newnode->prev = prev;
	prev->next = newnode;
	pos->prev = newnode;
}

void erase(sl* pos)
{
	assert(pos);

	sl* prev = pos->prev;
	sl* next = pos->next;

	free(pos);
	prev->next = next;
	next->prev = prev;
}

void destroy(sl* phead)
{
	sl* cur = phead->next;
	while (cur != phead)
	{
		sl* next = cur->next;
		free(cur);
		cur = next;
	}
	free(phead);
}